//
//  UdpClientUtil.m
//  TestTcpUdp
//
//  Created by leeson zhong on 2021/7/20.
//

#import "UdpClientUtil.h"
#import "GCDAsyncUdpSocket.h"

@interface UdpClientUtil()<GCDAsyncUdpSocketDelegate>{
    NSString *serverIp;
    int serverPort;
}

//客户端
@property (strong, nonatomic) GCDAsyncUdpSocket *clientSocket;

@end

@implementation UdpClientUtil

-(BOOL)initWithServerIp:(NSString *)ip Port:(int)port{
    self.clientSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    NSError *error = nil;
    BOOL result = [self.clientSocket bindToPort:0 error:&error];
    if (result == NO && self.delegate) {
        [self.clientSocket close];
        self.clientSocket = nil;
        [self.delegate onUdpClientClose];
    }else{
        serverIp = ip;
        serverPort = port;
        [self.clientSocket beginReceiving:&error];
    }
    return result;
}
-(BOOL)sendData:(NSData *)data{
    if (self.clientSocket) {
        [self.clientSocket sendData:data toHost:serverIp port:serverPort withTimeout:-1 tag:0];
        return YES;
    }else{
        return NO;
    }
}
-(void)close{
    if (self.clientSocket) {
        [self.clientSocket close];
    }
}

-(NSString *)getServerIp{
    return serverIp;
}
-(int)getServerPort{
    return serverPort;
}

#pragma GCDAsyncUdpSocketDelegate

/**
 * Called when the socket has received the requested datagram.
**/
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
                                             fromAddress:(NSData *)address
withFilterContext:(nullable id)filterContext{
    NSString *ip = [GCDAsyncUdpSocket hostFromAddress:address];
    int port = [GCDAsyncUdpSocket portFromAddress:address];
    
    if (serverIp && [serverIp isEqual:ip] && serverPort == port) {
        if (self.delegate) {
            [self.delegate onUdpClientReceiveData:data ServerIp:ip ServerPort:port];
        }
    }else{
        if (self.delegate) {
            [self.delegate onUdpClientReceiveNewConnectionIp:ip Port:port];
            [self.delegate onUdpClientReceiveData:data ServerIp:ip ServerPort:port];
        }
    }
    
    
}

/**
 * Called when the socket is closed.
**/
- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError  * _Nullable)error{
    if (self.clientSocket) {
        self.clientSocket = nil;
        if (self.delegate) {
            [self.delegate onUdpClientClose];
        }
    }
}


@end
